<template>
  <div>
    <n-modal v-model:show="showModal" :mask-closable="false" :show-icon="false" preset="dialog" v-bind:on-after-leave="closeModal"
      transform-origin="center" :title="formValue.id > 0 ? '编辑商品 #' + formValue.id : '添加商品'" :style="{
        width: dialogWidth,
      }">
      <n-scrollbar style="max-height: 87vh" class="pr-5">
        <n-spin :show="loading" description="请稍候...">
          <n-form ref="formRef" :model="formValue" :rules="rules"
            :label-placement="settingStore.isMobile ? 'top' : 'left'" :label-width="100" class="py-4">
            <n-grid cols="1 s:1 m:2 l:2 xl:2 2xl:2" responsive="screen">
              <n-gi span="1">
                <n-form-item label="商品名称" path="name">
                  <n-input placeholder="请输入商品名称" v-model:value="formValue.name" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="商品属性" path="type">
                  <n-radio-group v-model:value="formValue.type" name="type" @update:value="handleTypeChange">
                    <n-radio-button v-for="type in dict.getOptionUnRef('xxb_sp_sx')" :key="type.value"
                      :value="type.value" :label="type.label" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="商品主图" path="mainImage">
                  <UploadImage :maxNumber="3" v-model:value="formValue.mainImage" />
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="商品利益点" path="benefitPoints">
                  <n-dynamic-input v-model:value="formValue.benefitPoints" placeholder="请输入" :max="4" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 1 || formValue.type === 2">
                <n-form-item label="积分价格" path="integral">
                  <n-input-number placeholder="请输入积分价格" v-model:value="formValue.integral" min="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 2">
                <n-form-item label="物流价格" path="integralLogistics">
                  <n-input-number placeholder="请输入物流价格" v-model:value="formValue.integralLogistics" min="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 3">
                <n-form-item label="成本价" path="costPrice">
                  <n-input-number placeholder="请输入成本价" v-model:value="formValue.costPrice" min="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 3">
                <n-form-item label="销售价" path="salePrice">
                  <n-input-number placeholder="请输入销售价" v-model:value="formValue.salePrice" min="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="市场价格" path="marketPrice">
                  <n-input-number placeholder="请输入市场价格" v-model:value="formValue.marketPrice" min="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="会员专享" path="isMemberOnly">
                  <n-switch v-model:value="formValue.isMemberOnly" checked-value="1" unchecked-value="0" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="商品分类" path="categoryId">
                  <n-select v-model:value="formValue.categoryId" filterable multiple placeholder="选择商品分类" :loading="loadingCate" clearable remote :options="searchCateResults" @search="handleSearchCate" @update:value="handleChangeCate" label-field="label"  value-field="value" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="适用场景" path="scene">
                  <n-radio-group v-model:value="formValue.scene" name="scene">
                    <n-radio-button :key="1" :value="1" label="门店场景" v-if="formValue.type !== 2" />
                    <n-radio-button :key="2" :value="2" label="电商场景" v-if="formValue.type === 2" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="门店" path="storeId" v-if="formValue.scene === 1">
                  <n-select v-model:value="formValue.storeId" filterable multiple placeholder="选择门店" :loading="loadingStore" clearable
                    remote :options="searchStoreResults" @search="handleSearchStore" @update:value="handleSelectChange"
                    label-field="label"
                    value-field="value"
                  />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="描述" path="description">
                  <n-input type="textarea" placeholder="描述" v-model:value="formValue.description" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="规则说明" path="description" v-if="formValue.type === 3">
                  <n-input type="textarea" placeholder="规则说明" v-model:value="formValue.rules" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="配图" path="images">
                  <UploadImage :maxNumber="10" v-model:value="formValue.images" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 3 || formValue.type === 1">
                <n-form-item label="限购" path="restrictionType">
                  <n-radio-group v-model:value="formValue.restrictionType" name="restrictionType">
                    <n-radio-button v-for="restrictionType in dict.getOptionUnRef('xxb_sp_xglx')"
                      :key="restrictionType.value" :value="restrictionType.value" :label="restrictionType.label" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="1">
                <n-form-item label="每日限购" path="dailyPurchaseLimit">
                  <n-input-number placeholder="请输入限购数量" v-model:value="formValue.dailyPurchaseLimit" />
                </n-form-item>
              </n-gi>
              <n-gi span="1" v-if="formValue.restrictionType === 1 && (formValue.type === 3 || formValue.type === 1)">
                <n-form-item label="时间周期" path="cycle">
                  <n-radio-group v-model:value="formValue.cycle" name="cycle">
                    <n-radio-button v-for="cycle in dict.getOptionUnRef('xxb_sp_sjzq')" :key="cycle.value"
                      :value="cycle.value" :label="cycle.label" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="1" v-if="(formValue.restrictionType === 1 || formValue.restrictionType === 2) && (formValue.type === 3 || formValue.type === 1)">
                <n-form-item label="数量限制" path="quantityLimit">
                  <n-input-number placeholder="请输入数量限制" v-model:value="formValue.quantityLimit" />
                </n-form-item>
              </n-gi>
              <n-gi span="2">
                <n-form-item label="销氪/服务人员信息" path="salesType">
                  <n-radio-group v-model:value="formValue.salesType" name="salesType">
                    <n-radio-button v-for="salesType in dict.getOptionUnRef('xxb_sp_xxlx')" :key="salesType.value"
                      :value="salesType.value" :label="salesType.label" />
                  </n-radio-group>
                </n-form-item>
              </n-gi>
              <n-gi span="1" v-if="formValue.salesType === 2">
                <n-form-item label="销氪" path="agentId">
                  <n-select v-model:value="formValue.agentId" filterable placeholder="选择销氪" :loading="loadingUser" clearable
                    remote :options="searchResults" @search="handleSearch" />
                </n-form-item>
              </n-gi>
              <n-gi span="2" v-if="formValue.type === 3" >
                <n-form-item label="分享二维码" path="agentId">
                  <n-flex vertical inline>
                    <n-flex>
                      <n-button type="info" :loading="show" @click="qrCode">
                        点击生成
                      </n-button>
                    </n-flex>
                    <n-image width="150" :src="formValue.qrCode" />
                  </n-flex>
                </n-form-item>
              </n-gi>
              <n-gi span="1" v-if="formValue.type == 3">
                <n-form-item label="会员分销比例" path="vipProportion">
                  <n-input-number placeholder="请输入会员分销比例" v-model:value="formValue.vipProportion" min="0" max="100" :step="10">
                    <template #suffix>
                      %
                    </template>
                  </n-input-number>
                </n-form-item>
              </n-gi>
            </n-grid>
          </n-form>
        </n-spin>
      </n-scrollbar>
      <template #action>
        <n-space>
          <n-button @click="closeForm">
            取消
          </n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">
            确定
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { List } from '@/api/org/user';
import { Edit, View, categoryAll } from '@/api/product';
import { List as StoreList } from '@/api/store/index';
import { Qrcode } from '@/api/userModule';
import UploadImage from '@/components/Upload/uploadImage.vue';
import { useDictStore } from '@/store/modules/dict';
import { useProjectSettingStore } from '@/store/modules/projectSetting';
import { adaModalWidth } from '@/utils/hotgo';
import { useMessage } from 'naive-ui';
import { computed, ref } from 'vue';
import { State, newState, rules } from './model';

const emit = defineEmits(['reloadTable']);
const message = useMessage();
const settingStore = useProjectSettingStore();
const dict = useDictStore();
const loading = ref(false);
const loadingUser = ref(false);
const loadingStore = ref(false);
const loadingCate = ref(false);
const showModal = ref(false);
const formValue = ref<State>(newState(null));
const formRef = ref<any>({});
const formBtnLoading = ref(false);
const dialogWidth = computed(() => {
  return adaModalWidth(840);
});
const show = ref(false);
function closeModal() {
  formValue.value = newState(null);
}

// 提交表单
function confirmForm(e) {
  e.preventDefault();
  formRef.value.validate((errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      
      let storeId = formValue.value.storeId
      // 修改: 将 formValue.storeId 转换为所需的 JSON 格式
      formValue.value.storeId = JSON.stringify(storeJson.value);
      
      Edit(formValue.value)
        .then((_res) => {
          message.success('操作成功');
          closeForm();
          emit('reloadTable');
        }).catch(() => {
          formValue.value.storeId = storeId;
        })
        .finally(() => {
          formBtnLoading.value = false;
        });
    } else {
      message.error('请填写完整信息');
    }
  });
}

function handleTypeChange(value) {
  if (value === 2) {
    formValue.value.scene = 2;
  } else {
    formValue.value.scene = 1
  }
} 

// 关闭表单
function closeForm() {
  showModal.value = false;
  loading.value = false;
}

function qrCode(value) {
  
  show.value = true;  
  Qrcode({
    path: "pageC/pointGroup/pointGroup",
    scene: "store_id=" + formValue.value.id,
    isHyaline: false,
    type: 0,
  }).then((_res) => {
    if (_res?.qrCodeUrl) {
      formValue.value.qrCode = "https://imgs.ynz666.com/" + _res.qrCodeUrl
    } else {
      message.error('生成失败');
    }
    show.value = false;
  }).catch((_err) => {
    message.error('生成失败');
    show.value = false;
  });
}
// 打开模态框
function openModal(state: State) {
  showModal.value = true;

  // 默认查询一次数据
  handleSearch('');
  handleSearchStore('');
  handleSearchCate('')
  storeJson.value = []
  cateJson.value = []

  // 新增
  if (!state || state.id < 1) {
    formValue.value = newState(state);
    return;
  }

  // 编辑
  loading.value = true;
  View({ id: state.id })
    .then((res) => {
      formValue.value = res;
      // 修改: 将 formValue.storeId 转换为所需的 JSON 格式
      if (formValue.value.storeId) {
        searchStoreResults.value = formValue.value.storeId
        searchCateResults.value = formValue.value.categoryId
        formValue.value.storeId = searchStoreResults.value?.map(item => (item.value));
        formValue.value.categoryId = searchCateResults.value?.map(item => (item.value));
        storeJson.value = searchStoreResults.value;
        cateJson.value = searchCateResults.value

        if (formValue.value.id > 0) {
          List({ 
          id: formValue.value.agentId,
          roleIds: [211, 212]
        })
          .then((res) => {
            searchResults.value = res?.list?.map(item => ({
              label: item.mobile? item.realName + '（' + item.mobile + '）' : item.realName,
              value: item.id
            })) || [];
          })
          .catch((err) => {
          })
          .finally(() => {
          });
        }
      } else {
        handleSearchStore('');
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

// 新增的搜索结果存储变量
const storeJson = ref<{ label: string; value: number }[]>([]);
const searchResults = ref<{ label: string; value: number }[]>([]);
const searchStoreResults = ref<{ label: string; value: number }[]>([]);
const cateJson = ref<{ label: string; value: number }[]>([]);
const searchCateResults = ref<{ label: string; value: number }[]>([]);

// 实现 handleSearch 方法
function handleSearch(keyword: string) {
  if (loadingUser.value) return;
  loadingUser.value = true;
  List({ 
    realName: keyword,
    roleIds: [211, 212]
   })
    .then((res) => {
      searchResults.value = res?.list?.map(item => ({
        label: item.mobile? item.realName + '（' + item.mobile + '）' : item.realName,
        value: item.id
      })) || [];
    })
    .catch((err) => {
    })
    .finally(() => {
      loadingUser.value = false;
    });
}

function handleSelectChange(value: []) {
  storeJson.value = value.map(item => {
    return storeJson.value.find(item1 => item === item1.value)! || searchStoreResults.value.find(item1 => item === item1.value)!;
  });
}

function handleChangeCate(value: []) {
  cateJson.value = value.map(item => {
    return cateJson.value.find(item1 => item === item1.value)! || searchCateResults.value.find(item1 => item === item1.value)!;
  });
}

function handleSearchStore(keyword: string) {
  if (loadingStore.value) return;
  loadingStore.value = true;
  StoreList({ 
    name: keyword,
   })
    .then((res) => {
      searchStoreResults.value = res?.list?.map(item => ({
        label: item.name,
        value: item.id
      })) || [];
    })
    .catch((err) => {
    })
    .finally(() => {
      loadingStore.value = false;
    });
}
function handleSearchCate (keyword: string) {
  if (loadingCate.value) return;
  loadingCate.value = true;
  categoryAll({ 
    name: keyword,
   })
    .then((res) => {
      searchCateResults.value = res?.list?.map(item => ({
        label: item.name,
        value: item.id
      })) || [];
    })
    .finally(() => {
      loadingCate.value = false;
    });
}


defineExpose({
  openModal,
});
</script>

<style lang="less"></style>
